package com.cgc.venus.server.job.service;
import com.cgc.venus.server.core.base.AbstractBaseService;
import com.offbytwo.jenkins.JenkinsServer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by 业哥 on 2018/8/8.
 */
@Service
@ConfigurationProperties(prefix = "ci")
public class CIServiceImpl extends AbstractBaseService {
    private String jenkinsUrl;
    private String jenkinsUser;
    private String jenkinsPwd;

    public String getJenkinsUrl() {
        return jenkinsUrl;
    }

    public void setJenkinsUrl(String jenkinsUrl) {
        this.jenkinsUrl = jenkinsUrl;
    }

    public String getJenkinsUser() {
        return jenkinsUser;
    }

    public void setJenkinsUser(String jenkinsUser) {
        this.jenkinsUser = jenkinsUser;
    }

    public String getJenkinsPwd() {
        return jenkinsPwd;
    }

    public void setJenkinsPwd(String jenkinsPwd) {
        this.jenkinsPwd = jenkinsPwd;
    }
    private JenkinsServer jenkinsServer;

    public JenkinsServer getJenkinsServer() throws Exception {
        if (jenkinsServer != null) {
            boolean flag = jenkinsServer.isRunning();
            if (!flag) {
                throw new Exception("jenkins服务异常,请检查服务地址或者权限!");
            }
            return jenkinsServer;
        }
        URI serverUri = null;
        try {
            serverUri = new URI(jenkinsUrl);
            jenkinsServer = new JenkinsServer(serverUri, jenkinsUser, jenkinsPwd);
            boolean flag = jenkinsServer.isRunning();
            if (!flag) {
                throw new Exception("jenkins服务异常,请检查服务地址或者权限!");
            }
            return jenkinsServer;
        } catch (URISyntaxException e) {
            throw e;
        }
    }
}